﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using CarAppClient.Consts;
using CarAppClient.Controls.MessageUsercontrols;
using CarAppClient.Helpers;
using CarAppDto.Sys;
using CarAppDto.Sys.AdminDtos;
using CarAppDto.Sys.LoginDtos;
using D.Util.UtilCache;
using D.UtilCore.Dtos;
using D.UtilCore.JwtUtil;
using D.UtilCore.Models;
using D.WPF.MVVM;
using D.WPF.MVVM.EventUtil;
using Flurl.Http;
using HandyControl.Controls;
using Newtonsoft.Json;
using DelegateCommand = D.WPF.MVVM.EventUtil.DelegateCommand;

namespace CarAppClient.ViewModels
{
    /// <summary>
    /// 登录入参
    /// </summary>
    public class LoginVM : BaseMvvm
    {
        #region 系统信息

        private string systemTitle = "车联网系统";
        /// <summary>
        /// 标题
        /// </summary>
        public string SystemTitle
        {
            get { return systemTitle; }
            set { systemTitle = value; RaisePropertyChanged(); }
        }
        #endregion

        #region 窗体拖动

        /// <summary>
        /// 窗体
        /// </summary>
        private Login LoginUI;
        /// <summary>
        /// 背景
        /// </summary>
        private Grid GridBg;
        public LoginVM(Login login, Grid grid)
        {
            LoginUI = login;
            GridBg = grid;
            LoginUI.MouseLeftButtonDown += Login_MouseLeftButtonDown;
        }

        /// <summary>
        /// 拖动窗体事件重写
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Login_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // 获取鼠标相对标题栏位置  
            Point position = e.GetPosition(GridBg);

            // 如果鼠标位置在标题栏内，允许拖动  
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                if (position.X >= 0 && position.X < GridBg.ActualWidth && position.Y >= 0
                    && position.Y < GridBg.ActualHeight)
                {
                    LoginUI.DragMove();
                }
            }
        }
        #endregion

        #region 登录入参数据

        private string account = "admins";
        /// <summary>
        /// 账号
        /// </summary>
        public string Account
        {
            get { return account; }
            set { account = value; RaisePropertyChanged(); }
        }

        private string password = "123456";
        /// <summary>
        /// 密码
        /// </summary>
        public string Password
        {
            get { return password; }
            set { password = value; RaisePropertyChanged(); }
        }

        #endregion

        #region 登录命令
        /// <summary>
        /// 登录事件
        /// </summary>
        private DelegateCommandT<LoginVM> _loginCommand;
        /// <summary>
        /// 登录事件
        /// </summary>
        public DelegateCommandT<LoginVM> LoginCommand => _loginCommand ?? (_loginCommand = new DelegateCommandT<LoginVM>(Login));

        /// <summary>
        /// 登录函数
        /// </summary>
        /// <param name="loginVM"></param>
        private async void Login(LoginVM loginVM)
        {
            // 基础数据判断
            if (string.IsNullOrEmpty(loginVM.Account))
            {
                Growl.Warning("账号不可为空");
                return;
            }

            if (string.IsNullOrEmpty(loginVM.Password))
            {
                Growl.Warning("密码不可为空");
                return;
            }

            // 请求后端接口 
            var res = await HttpHelper<string>.PostAsync<ReqLogin>(ApiUrl.Login, new ReqLogin()
            {
                Account = loginVM.Account,
                Password = loginVM.Password
            }, false);

            //  判断结果
            if (res.Code == StatusCodeEnum.Waring)
            {
                MsgUtil.Warning(res.ErrorMsg);
            }
            else if (res.Code == StatusCodeEnum.ServerError)
            {
                Growl.Error("服务器异常");
            }
            else
            {
                // 存储Token信息
                var cache = AutoFacHelper.Instance.Get<ICacheService>();
                cache.Set(CacheKey.AccessToken, res.Data?.ToString());

                // 解析Token信息
                //var jwtService = AutoFacHelper.Instance.Get<IJwtService>();
                //var tokenInfo = jwtService.SerializeToken(res.Data.ToString());

                // 获取用户信息
                var apiResult = await HttpHelper<RepAdminInfo>.GetAsync($"{ApiUrl.GetAdminInfo}");
                if (apiResult.Code == StatusCodeEnum.OK)
                {
                    // 存储用户信息
                    cache.Set(CacheKey.UserName, apiResult.Data?.NickName);
                    cache.Set(CacheKey.Account, apiResult.Data?.Account);

                    // 初始化首页
                    MainWindow mainWindow = new MainWindow();
                    mainWindow.Show();

                    loginVM.LoginUI.Close();
                }
                else
                {
                    Growl.Warning("获取用户信息失败");
                }
            }
        }
        #endregion

        #region 退出命令
        /// <summary>
        /// 登录事件
        /// </summary>
        private DelegateCommand _exitCommand;
        /// <summary>
        /// 登录事件
        /// </summary>
        public DelegateCommand ExitCommand => _exitCommand ?? (_exitCommand = new DelegateCommand(Exit));

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="obj"></param>
        private void Exit(object? obj)
        {
            Application.Current.Shutdown();
        }
        #endregion
    }
}
